
import React, { useState, useEffect } from "react";
import { GlobalEvent } from "@/api/entities"; // Removed OperationalUnit
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
  Plus,
  Search,
  Calendar,
  Clock,
  AlertTriangle,
  Zap,
  CloudRain,
  Shield,
  Car,
  Ship,
  Train
} from "lucide-react";

import GlobalEventForm from "../components/global-events/GlobalEventForm";
import GlobalEventCard from "../components/global-events/GlobalEventCard";

export default function GlobalEvents() {
  const [globalEvents, setGlobalEvents] = useState([]);
  const [filteredEvents, setFilteredEvents] = useState([]);
  const [showEventForm, setShowEventForm] = useState(false);
  const [editingEvent, setEditingEvent] = useState(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedType, setSelectedType] = useState("all");
  const [isLoading, setIsLoading] = useState(true);


  useEffect(() => {
    loadData();
  }, []);

  useEffect(() => {
    filterEvents();
  }, [globalEvents, searchTerm, selectedType]);

  const loadData = async () => {
    setIsLoading(true);
    try {
      const eventsData = await GlobalEvent.list("-startDate");
      setGlobalEvents(Array.isArray(eventsData) ? eventsData : []);
    } catch (error) {
      console.error("加载数据失败:", error);
      setGlobalEvents([]);
    }
    setIsLoading(false);
  };

  const filterEvents = () => {
    let filtered = globalEvents;

    if (searchTerm) {
      filtered = filtered.filter(event =>
        event.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        event.description?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    if (selectedType !== "all") {
      filtered = filtered.filter(event => event.type === selectedType);
    }

    setFilteredEvents(filtered);
  };

  const handleEventSubmit = async (eventData) => {
    try {
      if (editingEvent) {
        await GlobalEvent.update(editingEvent.id, eventData);
      } else {
        await GlobalEvent.create(eventData);
      }
      setShowEventForm(false);
      setEditingEvent(null);
      loadData();
    } catch (error) {
      console.error("保存全局事件失败:", error);
      alert("保存全局事件失败: " + (error.message || "未知错误"));
    }
  };

  // Removed handleUnitSubmit as operational units are no longer managed here
  // const handleUnitSubmit = async (unitData) => { ... };

  const handleEditEvent = (event) => {
    setEditingEvent(event);
    setShowEventForm(true);
  };

  // Removed handleEditUnit as operational units are no longer managed here
  // const handleEditUnit = (unit) => { ... };

  const handleDeleteEvent = async (eventId) => {
    if (window.confirm("确定要删除此全局事件吗？此操作无法撤销。")) {
      try {
        await GlobalEvent.delete(eventId);
        loadData();
      } catch (error) {
        console.error("删除全局事件失败:", error);
        alert("删除全局事件失败，请稍后重试。");
      }
    }
  };

  // Removed handleDeleteUnit as operational units are no longer managed here
  // const handleDeleteUnit = async (unitId) => { ... };

  const handleCancel = () => {
    setShowEventForm(false);
    // setShowUnitForm(false); // Removed
    setEditingEvent(null);
    // setEditingUnit(null); // Removed
  };

  const getEventTypeIcon = (type) => {
    switch (type) {
      case 'peakPeriod': return <Zap className="w-5 h-5 text-red-500" />;
      case 'powerOutageWindow': return <Shield className="w-5 h-5 text-green-500" />;
      case 'roadClosureWindow': return <Car className="w-5 h-5 text-indigo-500" />;
      case 'navigationSuspensionWindow': return <Ship className="w-5 h-5 text-cyan-500" />;
      case 'transportSuspensionWindow': return <Train className="w-5 h-5 text-gray-700" />;
      case 'climateEvent': return <CloudRain className="w-5 h-5 text-blue-500" />;
      case 'supplyGuarantee': return <AlertTriangle className="w-5 h-5 text-orange-500" />;
      case 'holiday': return <Calendar className="w-5 h-5 text-purple-500" />;
      default: return <Clock className="w-5 h-5 text-gray-500" />;
    }
  };

  const getEventTypeName = (type) => {
    const typeMap = {
      peakPeriod: "高峰期",
      powerOutageWindow: "停电窗口",
      roadClosureWindow: "封路窗口",
      navigationSuspensionWindow: "停航窗口",
      transportSuspensionWindow: "停运窗口",
      climateEvent: "气候事件",
      supplyGuarantee: "保供电",
      holiday: "节假日"
    };
    return typeMap[type] || "其他";
  };

  const getStats = () => {
    return {
      totalEvents: globalEvents.length,
      outageWindows: globalEvents.filter(e => e.type === 'powerOutageWindow').length,
      peakPeriods: globalEvents.filter(e => e.type === 'peakPeriod').length,
      // Removed operational unit stats
      // totalUnits: operationalUnits.length,
      // constructionUnits: operationalUnits.filter(u => u.type === 'constructionUnit').length
    };
  };

  const stats = getStats();

  return (
    <div className="p-6 space-y-6 bg-gray-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6 mb-8">
          <div>
            <h1 className="text-3xl font-bold text-gray-900 mb-2">全局事件管理</h1>
            <p className="text-gray-600">管理影响工期的全局事件，包括停电窗口、封路窗口等时间约束</p>
          </div>
          <Button
            onClick={() => setShowEventForm(true)}
            className="bg-blue-600 hover:bg-blue-700 flex items-center gap-2"
          >
            <Plus className="w-4 h-4" />
            新建事件
          </Button>
        </div>

        {/* Removed Tabs section */}

        {/* Statistics */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6"> {/* Changed to md:grid-cols-3 as one card is removed */}
          <Card className="bg-gradient-to-r from-blue-50 to-blue-100 border-blue-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-blue-600">总事件数</p>
                  <p className="text-2xl font-bold text-blue-700">{stats.totalEvents}</p>
                </div>
                <Calendar className="w-8 h-8 text-blue-500" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-r from-green-50 to-green-100 border-green-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-green-600">停电窗口</p>
                  <p className="text-2xl font-bold text-green-700">{stats.outageWindows}</p>
                </div>
                <Shield className="w-8 h-8 text-green-500" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-r from-red-50 to-red-100 border-red-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-red-600">高峰期</p>
                  <p className="text-2xl font-bold text-red-700">{stats.peakPeriods}</p>
                </div>
                <Zap className="w-8 h-8 text-red-500" />
              </div>
            </CardContent>
          </Card>

          {/* Removed the Operational Units stat card */}
        </div>

        {/* Tab Content - Now directly displaying events content */}
        <>
          {/* Search and Filters */}
          <div className="flex flex-col lg:flex-row gap-4 mb-6">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
              <Input
                placeholder="搜索事件名称或描述..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
            <select
              value={selectedType}
              onChange={(e) => setSelectedType(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">所有类型</option>
              <option value="peakPeriod">高峰期</option>
              <option value="powerOutageWindow">停电窗口</option>
              <option value="roadClosureWindow">封路窗口</option>
              <option value="navigationSuspensionWindow">停航窗口</option>
              <option value="transportSuspensionWindow">停运窗口</option>
              <option value="climateEvent">气候事件</option>
              <option value="supplyGuarantee">保供电</option>
              <option value="holiday">节假日</option>
            </select>
            {/* Removed "新建事件" button from here as it's now in the header */}
          </div>

          {/* Event Form */}
          {showEventForm && (
            <GlobalEventForm
              event={editingEvent}
              onSubmit={handleEventSubmit}
              onCancel={handleCancel} // Updated to directly call handleCancel
            />
          )}

          {/* Events Grid */}
          <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
            {isLoading ? (
              Array(6).fill(0).map((_, i) => (
                <Card key={i} className="animate-pulse">
                  <CardHeader>
                    <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-2">
                      <div className="h-3 bg-gray-200 rounded"></div>
                      <div className="h-3 bg-gray-200 rounded w-2/3"></div>
                    </div>
                  </CardContent>
                </Card>
              ))
            ) : filteredEvents.length === 0 ? (
              <div className="col-span-full text-center py-12">
                <Calendar className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <h3 className="text-lg font-semibold text-gray-900 mb-2">暂无全局事件</h3>
                <p className="text-gray-500 mb-6">创建您的第一个全局事件来管理工期约束</p>
                <Button
                  onClick={() => setShowEventForm(true)}
                  className="bg-blue-600 hover:bg-blue-700"
                >
                  <Plus className="w-4 h-4 mr-2" />
                  新建事件
                </Button>
              </div>
            ) : (
              filteredEvents.map((event) => (
                <GlobalEventCard
                  key={event.id}
                  event={event}
                  onEdit={handleEditEvent}
                  onDelete={handleDeleteEvent}
                />
              ))
            )}
          </div>
        </>
        {/* Removed the entire 'units' tab content */}
      </div>
    </div>
  );
}
